package by.alex.dzeshko.facebooksuperclient;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import by.alex.dzeshko.facebooksuperclient.adapter.FriendsListCursorAdapter;
import by.alex.dzeshko.facebooksuperclient.api.ApiRequest;
import by.alex.dzeshko.facebooksuperclient.constants.FbConstants;
import by.alex.dzeshko.facebooksuperclient.database.DbFriendsHelper;
import by.alex.dzeshko.facebooksuperclient.http.RequestBuilder;
import by.alex.dzeshko.facebooksuperclient.providers.contract.FbContract;
import by.alex.dzeshko.facebooksuperclient.service.FeedService;
import by.alex.dzeshko.facebooksuperclient.service.FriendsService;
import by.alex.dzeshko.facebooksuperclient.service.ProfileService;
import by.alex.dzeshko.facebooksuperclient.utils.InetChecker;
import by.alex.dzeshko.facebooksuperclient.utils.ViewHider;

public class ListFriendsFragment extends ListFragment implements OnScrollListener {

	private static final String TAG = "tag";

	private static final String LOG_TAG = "ListFriendsFragment";

	private ListView mListViewFriends;
	
	private ImageButton mButtonRefresh;
	
	private View mViewLoading, mViewRefreshing;
	
	private String mNextPageUrl;
	
	private FriendsListCursorAdapter mFriendsAdapter;
	
	private BroadcastReceiver mBroadcastReceiver;

	private boolean mIsLoading, mViewLoadingHidden, mViewRefreshingHidden;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(true);
		LoaderManager loaderManager = getLoaderManager();
		loaderManager.initLoader(0, getArguments(), new LoaderCallbacks<Cursor>() {

			@Override
			public Loader<Cursor> onCreateLoader(int paramInt, Bundle paramBundle) {
				
				return new CursorLoader(getActivity(), FbContract.FriendsColumns.FRIENDS_CONTENT_URI, null, null, null, null);
			}

			@Override
			public void onLoadFinished(Loader<Cursor> paramLoader, Cursor paramD) {
				mFriendsAdapter.swapCursor(paramD);
			}

			@Override
			public void onLoaderReset(Loader<Cursor> paramLoader) {
				mFriendsAdapter.swapCursor(null);
			}
		});
		mBroadcastReceiver = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (action.equals(FriendsService.ACTION_ON_ERROR)) {
					hideViewRefreshing(true);
					hideViewLoading(true);
					mIsLoading = false;
					Toast.makeText(getActivity(),intent.getStringExtra(FriendsService.EXTRA_KEY_MESSAGE), Toast.LENGTH_SHORT).show();
				} else if (action.equals(FriendsService.ACTION_ON_SUCCESS)) {
					mIsLoading = false;
					if(!mViewRefreshingHidden) hideViewRefreshing(true);
					mNextPageUrl = intent.getStringExtra(FriendsService.NEXT_PAGE);
					Log.d("friends next url", mNextPageUrl );
					if(mNextPageUrl ==null || mNextPageUrl.equals(FeedService.NO_PAGES)) hideViewLoading(true);
				}
			}
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(FriendsService.ACTION_ON_ERROR);
		filter.addAction(FriendsService.ACTION_ON_SUCCESS);
		ContextHolder.getInstance().getContext().registerReceiver(mBroadcastReceiver, filter);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		ContextHolder.getInstance().getContext().unregisterReceiver(mBroadcastReceiver);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_list_friends, null);
		
		mIsLoading = false;
		mNextPageUrl = FeedService.NO_PAGES;
		mListViewFriends = (ListView)v.findViewById(android.R.id.list);
		mViewLoading = inflater.inflate(R.layout.view_listitem_loading, null);
		mViewRefreshing = inflater.inflate(R.layout.view_refreshig, null);
		mViewLoading.setTag(R.string.tag, TAG);
		mViewRefreshing.setTag(R.string.tag, TAG);
		mListViewFriends.addHeaderView(mViewRefreshing, null, false);
		mListViewFriends.addFooterView(mViewLoading, null, false);
		mFriendsAdapter = new FriendsListCursorAdapter(ContextHolder.getInstance().getContext(), null);
		mListViewFriends.setAdapter(mFriendsAdapter);
		hideViewRefreshing(true);
		hideViewLoading(true);
		mListViewFriends.setOnScrollListener(this);
		mButtonRefresh = (ImageButton) v.findViewById(R.id.btnRefresh);
		mButtonRefresh.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!InetChecker.checkInetConnection(getActivity())){ return; }
				mIsLoading=true;
				hideViewRefreshing(false);
				DbFriendsHelper dbHelper = new DbFriendsHelper(getActivity().getApplicationContext(), null);
				dbHelper.deleteTable();
				dbHelper.close();
				String url = ApiRequest.getFriends(getActivity().getString(R.string.graph_api_me));
				loadFriendListPage(url);
			}
		});

		return v;
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.d(LOG_TAG,"onResume");
		mFriendsAdapter.notifyDataSetChanged();
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		InetChecker.checkInetConnection(getActivity());
		try{
			Cursor cursor = (Cursor) l.getItemAtPosition(position);
			String friendId = cursor.getString(cursor.getColumnIndex(FbContract.FriendsColumns.ITEM_ID));
			showProfileActivity(friendId);
		}
		catch(Exception e){
			Log.e(LOG_TAG, e.toString());
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (visibleItemCount > 0 && firstVisibleItem + visibleItemCount + 3 >= totalItemCount && !mNextPageUrl.equals(FeedService.NO_PAGES)) {
			Log.d("onScroll","load");
			if(!mIsLoading){
				mIsLoading = true;
				if(mViewLoadingHidden) hideViewLoading(false);
				loadFriendListPage(mNextPageUrl);
			}
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView arg0, int arg1) {}
	
	private void showProfileActivity(String friendId){
		Intent loadProf = new Intent(getActivity(), ProfileService.class);
		RequestBuilder requestBuilder = new RequestBuilder();
		requestBuilder.setType(RequestBuilder.Type.GET);
		requestBuilder.setUrl(ApiRequest.getUserSimple(friendId)); 
		loadProf.putExtra(ProfileService.HTTP_REQUEST_BUILDER, requestBuilder);
		getActivity().startService(loadProf);
		Intent intent = new Intent(getActivity(), UserProfileActivity.class);
		intent.putExtra(FbConstants.ID, friendId);
		startActivity(intent);
	}
	
	public void loadFriendListPage(String url){
		Intent intent = new Intent(getActivity(), FriendsService.class);
		RequestBuilder requestBuilder = new RequestBuilder();
		requestBuilder.setType(RequestBuilder.Type.GET);
		requestBuilder.setUrl(url); 
		intent.putExtra(FriendsService.HTTP_REQUEST_BUILDER, requestBuilder);
		getActivity().startService(intent);
	}
	
	private void hideViewRefreshing(boolean hide){
		mViewRefreshingHidden=hide;
		ViewHider.hideListItem(mViewRefreshing, hide);
	}

	private void hideViewLoading(boolean hide){
		mViewLoadingHidden=hide;
		ViewHider.hideListItem(mViewLoading, hide);
	}

}
